package com.example.myapplication.module

import android.Manifest
import android.view.View
import com.example.myapplication.BuildConfig
import com.example.myapplication.R
import com.example.myapplication.databinding.ActivityLoginBinding
import com.example.myapplication.entity.AccsetBean
import com.example.myapplication.entity.CloudBean
import com.example.myapplication.entity.LoginUserBean
import com.example.myapplication.soaprequest.SoapEnvelop
import com.example.myapplication.soaprequest.request.*
import com.example.myapplication.widget.CustomerToolbar
import com.example.mylibrary.ActivityManager
import com.example.mylibrary.base.BaseMvpActivity
import com.example.mylibrary.utils.EquipmentUtil
import com.example.mylibrary.utils.GsonUtil
import com.example.mylibrary.utils.SpUtils
import com.example.mylibrary.utils.UiTools
import com.google.gson.reflect.TypeToken
import com.lxj.xpopup.impl.LoadingPopupView
import com.tbruyelle.rxpermissions2.RxPermissions

class LoginActivity : BaseMvpActivity<LoginActivity, LoginPresenter, ActivityLoginBinding>() {
    private val soapEnvelop = SoapEnvelop()
    private val soapRequestBody = SoapRequestBody()
    private val accsetRequest = AccsetRequest()
    private val accsetsaasRequest = AccsetsaasRequest()
    private val mobileRequest = MobileRequest()
    private val login = LoginRequest()
    private val loginUserBean = LoginUserBean()
    private var accsetBeanList: MutableList<AccsetBean> = mutableListOf()
    var loadPopup: LoadingPopupView? = null
    private lateinit var binding: ActivityLoginBinding

    private val settingDialog: SettingDialog by lazy {
        SettingDialog(this)
    }

    private val rxPermissions: RxPermissions by lazy {
        RxPermissions(this)
    }

    private val paramsMap = HashMap<String, String>()

    override fun getPresenter(): LoginPresenter = LoginPresenter()

    override fun getBinding(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }

    override fun initData() {
        // 取出存储的登录账号信息
        val loginUserAccount = SpUtils.get("loginUserAccount", "") as String
        if (loginUserAccount.isNotEmpty()) {
            // 不为空时, 设置记住账号密码状态,同时设置账号信息回显
            val loginUserBean = GsonUtil.fromJson(loginUserAccount, LoginUserBean::class.java)
            viewBinding.cbRemember.isChecked = loginUserBean.isRemember
            if (loginUserBean.isRemember) {
                viewBinding.etNumbering.setText(loginUserBean.userName)
                viewBinding.etPassword.setText(loginUserBean.pwd)
            }
        }

        loadPopup = builder.asLoading("加载中...")
        // 设置弹窗点击确认事件
        settingDialog.confirmClick = object : SettingDialog.ConfirmClick {
            override fun onConfirmClick(cloudList: MutableList<CloudBean>) {
                SpUtils.put("currentAccount", "")
                storeIpPort(cloudList)
            }
        }
        // 首次进入时存储ip和端口号
        storeIpPort(getCloudInfo())
    }

    /**
     * 存储选中的IP和端口号
     */
    private fun storeIpPort(cloudInfo: MutableList<CloudBean>) {
        for (cloudBean in cloudInfo) {
            if (cloudBean.cloudCheck) {
                SpUtils.put("host", cloudBean.ip)
                SpUtils.put("port", cloudBean.port)
                if (cloudBean.isPublic) {
                    // 公有云
                    paramsMap["vertype"] = BuildConfig.vertype
                    paramsMap["imei"] = "865166025718936"
                    paramsMap["usercode"] = cloudBean.userName
                    mPresenter?.getMobileReg(paramsMap)
                } else {
                    // 私有云
                    soapRequestBody.value = accsetRequest
                    soapEnvelop.body = soapRequestBody
                    mPresenter?.getAccountInfo(soapEnvelop)
                }
            }
        }
    }

    override fun initView() {
        viewBinding.clToolbar.clickListener = object : CustomerToolbar.ClickListener {
            override fun onBackListener() {
                ActivityManager.finishAll()
            }

            override fun onRightListener() {
                // 修改服务ip和端口号
                settingDialog.getDialog(getCloudInfo())
            }
        }
        viewBinding.tvChooseAccountService.setOnClickListener(this)
        viewBinding.btLogin.setOnClickListener(this)
    }


    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tvChooseAccountService -> {
                // 选择帐套信息
                if (accsetBeanList.size > 0) {
                    val arrayOf = arrayOfNulls<String>(accsetBeanList.size)
                    for (i in 0 until accsetBeanList.size) {
                        arrayOf[i] = accsetBeanList[i].name
                    }
                    builder.atView(viewBinding.tvChooseAccountService)
                        .asCenterList(
                            "", arrayOf
                        ) { position, text ->
                            viewBinding.tvChooseAccountService.text = text
                            val accsetBean = accsetBeanList[position]
                            val dbname = accsetBean.dbname
                            SpUtils.put("currentAccount", GsonUtil.toJson(accsetBean))
                            SpUtils.put("dbname", dbname)
                        }
                        .show()
                }
            }
            R.id.btLogin -> {
                val number = UiTools.getText(viewBinding.etNumbering)
                val pwd = UiTools.getText(viewBinding.etPassword)

                if (number.isEmpty()) {
                    UiTools.showToast(R.string.inputNumbering)
                    return
                }
                val cloudInfo = getCloudInfo()
                for (cloudBean in cloudInfo) {
                    if (cloudBean.cloudCheck) {
                        if (cloudBean.isPublic) {
                            // TODO: 2020-11-06 公有云登录暂时未做
                            // 公有云
                        } else {
                            // 私有云
                            val host = SpUtils.get("host", "") as String
                            val currentAccount = SpUtils.get("currentAccount", "") as String
                            if (currentAccount.isNotEmpty()) {
                                val accsetBean =
                                    GsonUtil.fromJson(currentAccount, AccsetBean::class.java)
                                login.dbname = accsetBean.dbname
                            }

                            if (host == "saas.hengshicrm.com") {
                                // host为saas 时,不验证手机直接登录
                                login.usercode = number
                                login.pwd = pwd
                                soapRequestBody.value = login
                                soapEnvelop.body = soapRequestBody
                                mPresenter?.login(soapEnvelop)
                            } else {
                                // host不为saas时,不验证手机直接登录
                                // 先验证手机是否已经注册了
                                rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
                                    .subscribe { isAgree ->
                                        if (isAgree) {
                                            val deviceId = EquipmentUtil.getDeviceId(this)
                                            mobileRequest.imei = deviceId
                                            mobileRequest.imei = "865166025718936"
                                            soapRequestBody.value = mobileRequest
                                            soapEnvelop.body = soapRequestBody
                                            mPresenter?.mobileReg(soapEnvelop)
                                        } else {
                                            UiTools.showToast("无法获取手机信息权限,请设置权限后再试")
                                        }
                                    }
                            }
                        }
                    }
                }
            }
        }
    }


    private val cloudMap = mutableListOf<CloudBean>()

    /**
     * 获取存储的服务器信息
     */
    private fun getCloudInfo(): MutableList<CloudBean> {
        cloudMap.clear()
        // 获取服务信息
        val serviceInfo = SpUtils.get("serviceInfo", "") as String
        if (serviceInfo.isNotEmpty()) {
            val cloudBeans = GsonUtil.fromJson<MutableList<CloudBean>>(
                serviceInfo,
                object : TypeToken<MutableList<CloudBean>>() {}.type
            )
            cloudMap.addAll(cloudBeans)
        } else {
            cloudMap.add(
                CloudBean(
                    cloudName = "私有云",
                    cloudCheck = true,
                    isPublic = false,
                    ip = "saas.hengshicrm.com",
                    port = "8031",
                    userName = ""
                )
            )
            cloudMap.add(
                CloudBean(
                    cloudName = "公有云",
                    cloudCheck = false,
                    isPublic = true,
                    ip = "saas.hengshicrm.com",
                    port = "8088",
                    userName = ""
                )
            )
            SpUtils.put(
                "serviceInfo",
                GsonUtil.toJson(cloudMap, object : TypeToken<MutableList<CloudBean>>() {}.type)
            )
        }
        for (cloudBean in cloudMap) {
            if (cloudBean.cloudCheck) {
                SpUtils.put("host", cloudBean.ip)
                SpUtils.put("port", cloudBean.port)
            }
        }
        return cloudMap
    }

    // 设置帐套信息
    fun setData(result: String) {
        if (result.isNotEmpty()) {
            accsetBeanList = GsonUtil.fromJson<MutableList<AccsetBean>>(
                result,
                object : TypeToken<MutableList<AccsetBean>>() {}.type
            )
        }

        // 初始化检测手机中是否保存了之前选的帐套信息,
        val currentAccount = SpUtils.get("currentAccount", "") as String
        if (currentAccount.isNotEmpty()) {
            val accsetBean = GsonUtil.fromJson<AccsetBean>(currentAccount, AccsetBean::class.java)
            viewBinding.tvChooseAccountService.text = accsetBean.name
        } else {
            viewBinding.tvChooseAccountService.text = accsetBeanList[0].name
            SpUtils.put("dbname", accsetBeanList[0].dbname)
            SpUtils.put("currentAccount", GsonUtil.toJson(accsetBeanList[0]))
        }
    }

    // 公有云验证手机是否已经注册
    fun setMobileSuccess() {
        soapRequestBody.value = accsetsaasRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.getAccsetsaas(soapEnvelop)
    }

    // 验证了手机信息已经注册
    fun mobileRegSuccess() {
        val number = UiTools.getText(viewBinding.etNumbering)
        val pwd = UiTools.getText(viewBinding.etPassword)
        login.usercode = number
        login.pwd = pwd

        soapRequestBody.value = login
        soapEnvelop.body = soapRequestBody
        mPresenter?.login(soapEnvelop)
    }

    // 登录成功
    fun loginSuccess() {
        loginUserBean.userName = login.usercode
        loginUserBean.pwd = login.pwd
        // 勾选了记住密码
        loginUserBean.isRemember = viewBinding.cbRemember.isChecked
        SpUtils.put("loginUserAccount", GsonUtil.toJson(loginUserBean))
        startNextActivity(this, null, MainActivity::class.java)
        finish()
    }
}